package org.meruvian.yama.controller;

import java.io.ObjectInputStream.GetField;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.meruvian.yama.entity.Person;
import org.meruvian.yama.form.PersonForm;
import org.meruvian.yama.service.PersonService;
import org.meruvian.yama.validator.PersonValidator;
import org.meruvian.yama.wrapper.PersonListWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * 
 * @author vick
 */
@Controller
public class PersonController {

	@Autowired
	private PersonService personService;

	@RequestMapping(value = "/person", method = RequestMethod.GET)
	public ModelAndView person(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView();
		System.out.println("Person OI");
		mv.addObject("person", new Person());
		mv.addObject("succeed", false);
		mv.addObject("failed", false);
		mv.setViewName("person/person-add");
		// mv.addObject(personService.getRelations());
		return mv;
	}

	@RequestMapping(value = "/person", method = RequestMethod.POST)
	public ModelAndView person(HttpServletRequest request,
			HttpServletResponse response,
			@ModelAttribute("person") PersonForm person,
			BindingResult bindingResult) {
		new PersonValidator().validate(person, bindingResult);
		System.out.println("--------------------" + person.getBirthDate());
		if (bindingResult.hasErrors()) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("person", person);
			mv.addObject("failed", "true");
			mv.addObject("succeed", "false");
			mv.setViewName("person/person-add");
			return mv;
		} else {
			// String relationId = person.getRelation().getId();
			// person.setRelation(personService.getRelation((relationId)));
			personService.save(person.getPerson());
			// if(!relationId.equalsIgnoreCase("")){
			// Person person2 = personService.getRelation((relationId));
			// person2.setRelation(person.getPerson());
			// personService.save(person2);
			// }
			ModelAndView mv = new ModelAndView();
			mv.addObject("person", person);
			mv.addObject("failed", "false");
			mv.addObject("succeed", "true");
			mv.setViewName("person/person-add");
			return mv;
		}
	}

	@RequestMapping(value = "person/{id}/listParent", method = RequestMethod.GET)
	public ModelAndView parentList(HttpServletRequest request,
			HttpServletResponse response, @PathVariable("id") String personId)
			throws Exception {
		List<Person> parents = personService.listParents(personId);
		ModelAndView mv = new ModelAndView("person/listParent");
		mv.addObject("list", parents);
		return mv;
	}

	@RequestMapping(value = "person/{id}/listChild", method = RequestMethod.GET)
	public ModelAndView childList(HttpServletRequest request,
			HttpServletResponse response, @PathVariable("id") String personId)
			throws Exception {
		Person person = personService.getPerson(personId);
		ModelAndView mv = new ModelAndView("person/listChild");
		mv.addObject(person);

		try {
			// String parentId = person.getParent().getId();
			List<Person> childs = personService.listChilds(personId, null);
			mv.addObject("list", childs);
		} catch (Exception e) {
			return mv;
		}
		return mv;
	}

	@RequestMapping(value = "person/listPerson/{sex}", method = RequestMethod.GET)
	public ModelAndView personList(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("sex") boolean sex)
			throws Exception {
		List<Person> persons = personService.listPersons(sex);
		ModelAndView mv = new ModelAndView("person/listPerson");
		mv.addObject("list", persons);
		return mv;
	}

	@RequestMapping(value = "/person/search", method = RequestMethod.GET)
	public ModelAndView search(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("person/person-search");
		return mv;
	}

	@RequestMapping(value = "/person/result", method = RequestMethod.POST)
	public ModelAndView builder(@RequestParam("firstName") String firstName) {
		StringBuilder builder = new StringBuilder();
		builder.append("result");
		if (!firstName.equalsIgnoreCase("")) {
			builder.append("/" + firstName);
		}
		ModelAndView mv = new ModelAndView(new RedirectView(builder.toString()));
		return mv;
	}

	@RequestMapping(value = "/person/result/{firstName}", method = RequestMethod.GET)
	public ModelAndView result(@PathVariable("firstName") String firstName) {
		ModelAndView mv = new ModelAndView();
		PersonListWrapper persons = new PersonListWrapper();
		persons.setPersons(personService.findPersons(firstName));
		mv.addObject("list", persons);
		mv.setViewName("person/person-result");
		return mv;
	}

	@RequestMapping(value = "/person/result", method = RequestMethod.GET)
	public ModelAndView result(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PersonListWrapper persons = new PersonListWrapper();
		persons.setPersons(personService.getPersons());
		ModelAndView mv = new ModelAndView("person/person-result");
		mv.addObject("list", persons);
		return mv;
	}

	@RequestMapping(value = "/person/child/{id}", method = RequestMethod.GET)
	public ModelAndView listPersonChild(@PathVariable("id") String personId) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("person/person-detail");
		PersonListWrapper childs = new PersonListWrapper();
		childs.setPersons(personService.getChilds(personId, null));
		mv.addObject("childs", childs);
		return mv;
	}

	@RequestMapping(value = "/person/{id}/detail", method = RequestMethod.GET)
	public ModelAndView detailPerson(@PathVariable("id") String personId) {
		// Person person = (Person) personService.getById(Person.class,
		// personId);
		Person person = personService.getPerson(personId);
		ModelAndView mv = new ModelAndView();
		mv.setViewName("person/person-detail");
		mv.addObject("person", person);
		PersonListWrapper childs = new PersonListWrapper();
		childs.setPersons(personService.getChilds(personId, null));
		mv.addObject("childs", childs);
		/**
		 * try{ String relationId = person.getRelation().getId(); List<Person>
		 * childs = personService.getChilds(personId, relationId);
		 * mv.addObject("childs",childs); }catch (NullPointerException e) {
		 * List<Person> childs = personService.getChilds(personId, null);
		 * mv.addObject("childs",childs); } try{ String parentId =
		 * person.getParent().getId(); Person parent =
		 * personService.getParent(parentId); mv.addObject("parent",parent);
		 * 
		 * }catch (NullPointerException e) { }
		 */
		return mv;
	}

	@RequestMapping(value = "/person/detail/{id}/parent", method = RequestMethod.POST)
	public ModelAndView addParent(@PathVariable("id") String personId,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("person") PersonForm person,
			BindingResult bindingResult) {
		String parentId = person.getParent().getId();
		Person person2 = personService.getPerson(personId);
		person2.setParent(personService.getParent((parentId)));
		personService.save(person2);

		String childId = person.getChildId();
		System.out.println(childId);
		/*
		 * if(!parentId.equalsIgnoreCase("")){ Person person2 =
		 * personService.getParent((parentId));
		 * person2.setRelation(person.getPerson()); personService.save(person2);
		 * }
		 */

		return new ModelAndView(new RedirectView(request.getContextPath()
				+ "/person/detail/" + personId));

	}

	@RequestMapping(value = "/person/{id}/child", method = RequestMethod.POST)
	public ModelAndView addChild(@PathVariable("id") String personId,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("person") PersonForm person,
			BindingResult bindingResult) {

		String childId = person.getChildId();
		Person child = personService.getPerson(childId);
		child.setParent(personService.getParent(personId));
		personService.save(child);
		/*
		 * if(!parentId.equalsIgnoreCase("")){ Person person2 =
		 * personService.getParent((parentId));
		 * person2.setRelation(person.getPerson()); personService.save(person2);
		 * }
		 */

		return new ModelAndView(new RedirectView(request.getContextPath()
				+ "/person/" + personId + "/redirect"));

	}

	@RequestMapping(value = "/person/{id}/redirect", method = RequestMethod.GET)
	public ModelAndView redirect(@PathVariable("id") String personId,
			HttpServletRequest request) {
		Person person = personService.getPerson(personId);
		ModelAndView mv = new ModelAndView();
		mv.setViewName("person/child-success");
		mv.addObject(person);
		return mv;
	}

	@RequestMapping(value = "/person/{id}/edit", method = RequestMethod.GET)
	public ModelAndView updatePerson(@PathVariable("id") String personId) {
		Person person = personService.getPerson(personId);
		SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("person/person-edit");
		mv.addObject("person", person);
		mv.addObject("dating",format.format(person.getBirthDate()));
		return mv;
	}

	@RequestMapping(value = "/person/{id}/edit", method = RequestMethod.POST)
	public ModelAndView updatePerson(HttpServletRequest request,
			@ModelAttribute("person") PersonForm person,
			BindingResult bindingResult) {
		new PersonValidator().validate(person, bindingResult);
		if (bindingResult.hasErrors()) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("person", person);
			mv.setViewName("person/person-edit");
			return mv;
		} else {
			personService.save(person.getPerson());
			return new ModelAndView(new RedirectView(request.getContextPath()
					+ "/person/result"));
		}
	}

	@RequestMapping(value = "/person/{id}/delete", method = RequestMethod.GET)
	public ModelAndView deletePerson(HttpServletRequest request,
			@PathVariable("id") String personId) {

		// Person a = (Person) personService.getById(Person.class, personId);

		for (Person child : personService.getChilds(personId, null)) {
			System.out.println(child.getId());
			child = personService.getPerson(child.getId());
			child.setParent(null);
			personService.save(child);

		}

		Person person = personService.getPerson(personId);
		// Person relation =
		// personService.getRelation(person.getRelation().getId());
		// person.setRelation(null);
		// relation.setRelation(null);
		// personService.save(relation);
		// personService.save(person);
		// Person s = personService.getPerson(person.getId());
		personService.delete(person);
		return new ModelAndView(new RedirectView(request.getContextPath()
				+ "/person/result"));
	}

	@RequestMapping(value = "/person/{id}/deleteChild", method = RequestMethod.GET)
	public ModelAndView deleteChild(HttpServletRequest request,
			@PathVariable("id") String personId) {
		Person person = personService.getPerson(personId);
		String parentId = person.getParent().getId();
		person.setParent(null);
		personService.save(person);
		return new ModelAndView(new RedirectView(request.getContextPath()
				+ "/person/" + parentId + "/detail"));
	}

	@RequestMapping(value = "/person/{id}/newChild", method = RequestMethod.GET)
	public ModelAndView newChild(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("person", new Person());
		mv.setViewName("person/person-newChild");
		return mv;
	}

	@RequestMapping(value = "/person/{id}/newChild", method = RequestMethod.POST)
	public ModelAndView newChild(HttpServletRequest request,
			HttpServletResponse response, @PathVariable("id") String personId,
			@ModelAttribute("person") PersonForm person,
			BindingResult bindingResult) {
		new PersonValidator().validate(person, bindingResult);
		if (bindingResult.hasErrors()) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("person", person);
			mv.setViewName("person/person-newChild");
			return mv;
		} else {
			person.getPerson().setParent(personService.getParent(personId));
			personService.save(person.getPerson());

			return new ModelAndView(new RedirectView(request.getContextPath()
					+ "/person/" + personId + "/redirect"));

		}
	}

}
